<?php
/**
 * Created by PhpStorm.
 * User: linyida
 * Date: 2019/7/27
 * Time: 上午9:54
 */
namespace App\Storage;

use EasySwoole\Component\Singleton;
use EasySwoole\RedisPool\Redis;

class ServiceRoleRedis {

    use Singleton;
    protected $table = "shop_server";

    function __construct($shopId)
    {
        $this->table = $this->table . '_' . $shopId;
    }

    /**
     * 缓存所有的客服角色。key 是$shopId，value是用户信息["shop_id","role_id","shop_user_id","status"]
     * @param $shopId
     * @param $data
     */
    function add($shopId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        $data = ServiceRole::getInstance()->read(['shop_id' => $shopId]); // sql中查出来
        if (isset($data) && !empty($data)) {
            return $redis->setEx($this->table, 300, json_encode($data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); // 存300秒
        }
    }

    /**
     * 获取所有的客服角色
     * @param $userId
     * @return mixed
     */
    function get($shopId) {
        $redis = Redis::getInstance()->pool('redis')::defer();
        $data = $redis->get($this->table);
        if ($data) {
            return json_decode($data,true);
        } else {
            $this->add($shopId);
            $this->get($shopId);
        }
    }

}